<template>
  <div class="app-container">
    <div v-if="tabsData.length === 0">
      <el-empty description="没有数据" />
    </div>
    <div v-else>
      <el-tabs v-model="tabsActive" type="card" @tab-click="selectTab">
        <el-tab-pane v-for="tabName in tabsData" :key="tabName" :label="tabName" :name="tabName" />
      </el-tabs>
      <el-form :inline="true" :model="searchFormData" class="demo-form-inline" @submit.native.prevent>
        <el-form-item label="路由名称">
          <el-input v-model="searchFormData.id" :clearable="true" placeholder="输入接口名或版本号" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="searchFormData.permission">授权接口</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="searchFormData.needToken">需要token</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" native-type="submit" @click="onSearchTable">查询</el-button>
        </el-form-item>
      </el-form>
      <el-button
        v-show="isCustomService"
        type="primary"

        icon="Plus"
        @click.stop="addRoute"
      >
        新建路由
      </el-button>
      <el-table
        :data="pageInfo.rows"
        border
        highlight-current-row
        style="margin-top: 10px;"
      >
        <el-table-column
          prop="name"
          label="接口名 (版本号)"
        >
          <template #default="scope">
            {{ getNameVersion(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="roles"
          label="访问权限"
          width="150"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <span v-if="!scope.row.permission">
              （公开）
            </span>
            <span v-else class="roles-content" @click="onTableAuth(scope.row)" v-html="roleRender(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column
          prop="ignoreValidate"
          label="签名校验"
          width="120"
        >
          <template #default="scope">
            <span v-if="scope.row.ignoreValidate === 0">校验</span>
            <span v-if="scope.row.ignoreValidate === 1" style="color:#E6A23C">不校验</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="mergeResult"
          label="统一格式输出"
          width="120"
        >
          <template #default="scope">
            <span v-if="scope.row.mergeResult === 1">是</span>
            <span v-if="scope.row.mergeResult === 0" style="color:#E6A23C">否</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="needToken"
          label="需要token"
          width="120"
        >
          <template #default="scope">
            <span v-if="scope.row.needToken === 1" style="font-weight: bold;color: #303133;">是</span>
            <span v-if="scope.row.needToken === 0">否</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="80"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="2"
              @change="onChangeStatus(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="margin-top: 5px"
        :current-page="searchFormData.pageIndex"
        :page-size="searchFormData.pageSize"
        :page-sizes="[10, 20, 40]"
        :total="pageInfo.total"
        layout="total, sizes, prev, pager, next"
        @size-change="onSizeChange"
        @current-change="onPageIndexChange"
      />
    </div>
    <!-- route dialog -->
    <el-dialog
      :title="routeDialogTitle"
      v-model="routeDialogVisible"
      :close-on-click-modal="false"
      @close="onCloseRouteDialog"
    >
      <el-form
        ref="routeDialogFormRef"
        :model="routeDialogFormData"
        :rules="routeDialogFormRules"
        label-width="180px"

      >
        <el-input v-show="false" v-model="routeDialogFormData.id" />
        <el-form-item label="接口名 (版本号)">
          {{ routeDialogFormData.name + (routeDialogFormData.version ? ' (' + routeDialogFormData.version + ')' : '') }}
        </el-form-item>
        <el-form-item label="签名校验">
          {{ routeDialogFormData.ignoreValidate ? '不校验' : '校验' }}
        </el-form-item>
        <el-form-item label="统一格式输出">
          {{ routeDialogFormData.mergeResult === 1 ? '是' : '否' }}
        </el-form-item>
        <el-form-item label="需要token">
          {{ routeDialogFormData.needToken === 1 ? '是' : '否' }}
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="routeDialogFormData.status">
            <el-radio :label="1" name="status">启用</el-radio>
            <el-radio :label="2" name="status" style="color:#F56C6C">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="routeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onRouteDialogSave">保 存</el-button>
      </div>
    </el-dialog>
    <!-- auth dialog -->
    <el-dialog
      title="路由授权"
      v-model="authDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="authDialogFormData"
        label-width="120px"

      >
        <el-form-item label="路由ID">
          <span>{{ authDialogFormData.routeId }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group v-model="authDialogFormData.roleCode">
            <el-checkbox v-for="item in roles" :key="item.roleCode" :label="item.roleCode">{{ item.description }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="authDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onAuthDialogSave">保 存</el-button>
      </div>
    </el-dialog>
    <!--添加服务-->
    <el-dialog
      title="添加服务"
      v-model="addServiceDialogVisible"
      :close-on-click-modal="false"
      @close="closeAddServiceDlg"
    >
      <el-form
        ref="addServiceFormRef"
        :model="addServiceForm"
        :rules="addServiceFormRules"
        label-width="200px"
      >
        <el-form-item label="服务名（serviceId）" prop="serviceId">
          <el-input v-model="addServiceForm.serviceId" placeholder="服务名，如：order-service" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addServiceDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onAddService">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .el-input.is-disabled .el-input__inner {color: #909399;}
  .el-radio__input.is-disabled+span.el-radio__label {color: #909399;}
  .roles-content { cursor: pointer;color: #20a0ff }
</style>
<script setup>
import { ref,onMounted, reactive, watch,nextTick } from 'vue';
import { useMessageBox } from '@/hooks/message';
import request from '@/utils/request';
const tabsData=ref([])
const tabsActive=ref('')
const serviceTextLimitSize=20
const filterText=ref('')
const treeData=ref([])
const tableData=ref([])
const serviceId=ref('')
const isCustomService=ref(false)
const searchFormData=reactive({
  id: '',
  serviceId: '',
  permission: 0,
  needToken: 0,
  pageIndex: 1,
  pageSize: 10
})
const pageInfo=reactive({
  rows: [],
  total: 0
})
const defaultProps=reactive({
  children: 'children',
  label: 'label'
})
const routeDialogTitle=ref('修改路由')
const routeDialogFormRef=ref()
      // dialog
const routeDialogFormData=reactive({
  id: '',
  name: '',
  version: '1.0',
  uri: '',
  path: '',
  status: 1,
  mergeResult: 1,
  ignoreValidate: 0
})
const routeDialogFormRules=reactive({
  name: [
    { required: true, message: '不能为空', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  version: [
    { required: true, message: '不能为空', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  uri: [
    { required: true, message: '不能为空', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  path: [
    { min: 0, max: 100, message: '长度不能超过 100 个字符', trigger: 'blur' }
  ]
})
const routeDialogVisible=ref(false)
const roles=ref([])
const authDialogFormData=reactive({
  routeId: '',
  roleCode: []
})
const authDialogVisible=ref(false)
      // addService
const addServiceDialogVisible=ref(false)
const addServiceFormRef=ref()
const addServiceForm=reactive({
  serviceId: ''
})
const addServiceFormRules=reactive({
  serviceId: [
    { required: true, message: '请输入服务名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ]
})
const loadTabs=async()=> {
  const resp=await request('/api/registry/service/list', {})
  tabsData.value = resp.data
  await nextTick()
  if (tabsData.value.length > 0) {
    tabsActive.value = tabsData.value[0]
    loadRouteData()
  }
}
// 加载树
const loadTree=async()=> {
  const resp=await request('registry.service.list', {})
  const respData = resp.data
  treeData.value = convertToTreeData(respData, 0)
  await nextTick()
  // 高亮已选中的
  if (serviceId.value) {
    serviceTree.setCurrentKey(serviceId)
  }
}
// 树搜索
const filterNode=(value, data)=>{
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
// 树点击事件
const onNodeClick=(data, node, tree)=>{
  if (data.parentId) {
    serviceId.value = data.label
    searchFormData.serviceId = serviceId
    isCustomService.value = Boolean(data.custom)
    loadTable()
  }
}
const selectTab=()=> {
  loadRouteData()
}
const loadRouteData=()=> {
  serviceId.value = tabsActive
  searchFormData.serviceId = serviceId
  loadTable()
}
    /**
     * 数组转成树状结构
     * @param data 数据结构 [{
        "_parentId": 14,
        "gmtCreate": "2019-01-15 09:44:38",
        "gmtUpdate": "2019-01-15 09:44:38",
        "id": 15,
        "isShow": 1,
        "name": "用户注册",
        "orderIndex": 10000,
        "parentId": 14
    },...]
     * @param pid 初始父节点id，一般是0
     * @return 返回结果 [{
      label: '一级 1',
      children: [{
        label: '二级 1-1',
        children: [{
          label: '三级 1-1-1'
        }]
      }]
    }
     */
const convertToTreeData=(data, pid)=> {
  const result = []
  const root = {
    label: data.length === 0 ? '无服务' : '服务列表',
    parentId: pid
  }
  const children = []
  for (let i = 0; i < data.length; i++) {
    const child = { parentId: 1, label: data[i] }
    children.push(child)
  }
  root.children = children
  result.push(root)
  return result
}
const getNameVersion=(row)=> {
  return row.name + (row.version ? ' (' + row.version + ')' : '')
}
// table
const loadTable=async(param)=> {
  if (!searchFormData.serviceId) {
    useMessage().success('请选择一个服务', 'error')
    return;
  }
  const postData = param || searchFormData
  const resp=await request('/api/route/page', postData)
  Object.assign(pageInfo,resp.data)
}
const onSearchTable=()=> {
  searchFormData.pageIndex = 1
  loadTable()
}
const onTableUpdate=async(row)=> {
  routeDialogTitle.value = '修改路由'
  routeDialogVisible.value = true
  await nextTick()
  Object.assign(routeDialogFormData, row)
}
const onTableAuth=async(row)=>{
  authDialogFormData.routeId = row.id
  const searchData = { id: row.id, serviceId: serviceId }
  const resp=await request('route.role.get', searchData)
  const roleList = resp.data
  const roleCodes = []
  for (let i = 0; i < roleList.length; i++) {
    roleCodes.push(roleList[i].roleCode)
  }
  authDialogFormData.roleCode = roleCodes
  authDialogVisible.value = true
}
const onTableDel=(row)=> {
  useMessageBox().confirm(`确认要删除路由【${row.id}】吗？`).then(async()=>{
    const data = {
      serviceId: serviceId,
      id: row.id
    }
    const resp=await request('/api/route/del', data)
    useMessage().success('删除成功')
    loadTable()
  })
}
// element-plus switch开关 点击按钮后，弹窗确认后再改变开关状态
// https://blog.csdn.net/Gomeer/article/details/103697593
const onChangeStatus=(row)=>{
  const newStatus = row.status
  const oldStatus = newStatus === 1 ? 2 : 1
  // 先将状态改成原来的值
  row.status = oldStatus
  const nameVersion = getNameVersion(row)
  const msg = oldStatus === 1 ? `确认要禁用 ${nameVersion} 吗？` : `确认要启用 ${nameVersion} 吗？`
  useMessageBox().confirm(msg).then(async()=>{
    const data = {
      id: row.id,
      status: newStatus
    }
    // 'route.role.update', authDialogFormData
    const resp=await request('route.status.update', data)
    row.status = newStatus
  }).catch(()=>{
    row.status = oldStatus
  })
}
const onCloseRouteDialog=()=> {
  //resetForm('routeDialogFormRef')
  routeDialogFormRef.value.resetFields();
}
const routePropDisabled=()=>{
  if (!routeDialogFormData.id) {
    return false
  }
  return !isCustomService
}
const loadRouteRole=async()=>{
  if (roles.length === 0) {
    const resp=await request('/api/role/listAll', {})
    roles.value = resp.data
  }
}
const addRoute=async()=>{
  routeDialogTitle.value = '新建路由'
  routeDialogVisible.value = true
  await nextTick()
  Object.assign(routeDialogFormData, {
      id: ''
    })
}
const roleRender=(row)=> {
  const html = []
  const roles = row.roles
  for (let i = 0; i < roles.length; i++) {
    html.push(roles[i].description)
  }
  return html.length > 0 ? html.join(', ') : '点击授权'
}
const onRouteDialogSave=()=> {
  routeDialogFormRef.value.validate(async(valid) => {
    if (valid) {
      const uri = routeDialogFormData.id ? 'route.status.update' : 'route.add'
      routeDialogFormData.serviceId = serviceId
      const resp=await request(uri, routeDialogFormData)
      routeDialogVisible.value = false
      loadTable()
    }
  })
}
const onAuthDialogSave=async()=> {
  const resp=await request('/api/route/role/update', authDialogFormData)
  authDialogVisible.value = false
    loadTable()
}
const addService=()=>{
  addServiceDialogVisible.value = true
}
const closeAddServiceDlg=()=>{
  addServiceFormRef.value.resetFields()
}
const onAddService=()=>{
  addServiceFormRef.value.validate(async(valid) => {
    if (valid) {
      const resp=await request('/api/service/custom/add', addServiceForm)
      addServiceDialogVisible.value = false
      useMessage().success('添加成功')
      loadTree()
    }
  })
}
const onDelService=(data)=> {
  const serviceId = data.serviceId
  useMessageBox().confirm('确认要删除服务' + serviceId + '吗，【对应的路由配置会一起删除】').then(async()=>{
    const postData = {
      serviceId: serviceId
    }
    const resp=await request('/api/service/custom/del', postData)
    useMessage().success('删除成功')
    loadTree()
  })
}
const onSizeChange=(size)=>{
  searchFormData.pageSize = size
  loadTable()
}
const onPageIndexChange=(pageIndex)=> {
  searchFormData.pageIndex = pageIndex
  loadTable()
}
onMounted(()=>{
  loadTabs()
  loadRouteRole()
})
watch(filterText,()=>{
  serviceTree.filter(val)
})
</script>
